# -*- coding: utf-8 -*-
from django.shortcuts import get_object_or_404
from django.contrib.contenttypes.models import ContentType

from pygameweb.comments.forms import CommentForm
from pygameweb.comments.models import Comment

def generic_comment_wrapper(request, model , generic_view, generic_kwargs={}, object_id=None, slug=None):
    """
    this generic comment wrapper cuts in to a generic view (normally object_detail) ,creates a 
    comment form and checks for submited comment. Finally, it calls and returns generic view that is specified by
    generic_view parameter.
    """ 
    extra_context = comment_view(request,  model , object_id=object_id, slug=slug, slug_field=generic_kwargs.get("slug_field", "slug"),)
    #if extra_context is already specified, update it 
    if generic_kwargs.has_key("extra_context"):
        generic_kwargs["extra_context"].update(extra_context)
    else:  #else create extra_context
        generic_kwargs["extra_context"]=extra_context

    if object_id:
        return generic_view(request, object_id=object_id,   **generic_kwargs )
    else:
        return generic_view(request, slug=slug,  **generic_kwargs )
    
    
def comment_view(request,  model , object_id=None, slug=None, slug_field = None):
    #find lookup parameter(id,slug etc.) to get the related object. this is the same thing what django's generic views do
    if object_id:
        lookup = {"id":object_id}
    else:
        lookup = {slug_field or "slug": slug}    
        
    #get object 
    object = get_object_or_404(model, **lookup)
    preview = False
    confirm_delete = False
    comment_id = None
    action = "Add"
    if request.user.is_authenticated():
        form = CommentForm()
        # confirmed delete
        if (request.method == 'POST' and 'comment_delete' in request.POST and
            'comment_id' in request.POST):
            comment = get_object_or_404(Comment, id=request.POST["comment_id"])
            if comment.get_user_perms(request.user)[1]:
                comment.delete()
                request.user.message_set.create(
                            message="Your comment has been deleted")
            else:
                request.user.message_set.create(
                            message="You are not allowed to delete this comment!")
        # delete/edit request
        if (request.method == 'POST' and 'comment_edit' in request.POST and
            'comment_id' in request.POST):
            comment = get_object_or_404(Comment, id=request.POST["comment_id"])
            action_ = request.POST["comment_edit"]
            perms = comment.get_user_perms(request.user)
            if action_ == "delete":
                if perms[1]:
                    confirm_delete = True
                    form = None
                    comment_id = comment.id
                else:
                    request.user.message_set.create(
                            message="You are not allowed to delete this comment!")
            elif action_ == "edit":
                if perms[0]:
                    form = CommentForm(instance=comment)
                    action = "Edit"
                else:
                    request.user.message_set.create(
                            message="You are not allowed to edit this comment!")
        elif request.method == 'POST' and request.POST.has_key("content"):
            #create, bound form and create comment if its valid 
            instance = Comment(content_object = object, user = request.user)
            if "id" in request.POST and request.POST["id"]:                
                if instance.get_user_perms(request.user)[0]:
                    instance = get_object_or_404(Comment, 
                                             id=request.POST["id"])
                    action = "Edit"
                else:
                    request.user.message_set.create(
                            message="You are not allowed to edit this comment!")
                
            form = CommentForm(request.POST, instance=instance)
            if form.is_valid():
                if "submit" in request.POST:
                    if action == "Add":
                        form.save()
                        request.user.message_set.create(
                                    message="Your comment posted successfully")
                    elif action == "Edit":
                        comment = form.save(commit=False)
                        comment.last_editor = request.user
                        comment.save()
                        request.user.message_set.create(
                                    message="Changed your comment successfully")
                    form = CommentForm()
                else:
                    preview = form.save(commit=False)
                    preview.render_markup()
            
        
    else:  #user not signed in
        form = None

    content_type = ContentType.objects.get_for_model( model )
    comments = Comment.objects.filter(content_type = content_type, object_id = object.id )
    return {"comment_form":form, "comments":comments, 
            "comment_preview":preview, "confirm_delete":confirm_delete,
            "comment_id":comment_id, "comment_action":action}
